package com.sc.web.goods;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sc.dal.dto.promotion.PromotionGoodsSkuDto;
import com.sc.dal.model.ParamMap;
import com.sc.dal.model.base.BaseSku;
import com.sc.dal.model.goods.Goods;
import com.sc.dal.model.goods.GoodsBrand;
import com.sc.dal.model.goods.GoodsClass;
import com.sc.dal.model.goods.GoodsUnit;
import com.sc.dal.model.system.UserFormMap;
import com.sc.service.base.BaseSkuService;
import com.sc.service.goods.GoodsBrandService;
import com.sc.service.goods.GoodsClassService;
import com.sc.service.goods.GoodsService;
import com.sc.service.goods.GoodsSkuService;
import com.sc.service.goods.GoodsUnitService;
import com.sc.service.promotion.PromotionService;
import com.sc.util.data.Common;
import com.sc.util.data.DataUtil;
import com.sc.util.data.DateUtil;
import com.sc.util.data.JsonUtils;
import com.sc.util.data.PinyinUtil;
import com.sc.util.exception.ExceptionEnum;
import com.sc.util.exception.ScBizException;
import com.sc.util.openAPI.OpenAPI;
import com.sc.web.BaseController;
import com.sc.web.plugin.PageView;

/**
 * 商品管理
 * @author maoyongbin
 * @日期 Mar 15, 2017 9:59:34 AM
 */
@Controller
@RequestMapping(value="goods")
public class GoodsController extends BaseController{
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private GoodsClassService goodsClassService;
	@Autowired
	private GoodsUnitService goodsUnitService;
	@Autowired
	private GoodsBrandService goodsBrandService;
	@Autowired
	private GoodsSkuService goodsSkuService;
	@Autowired
	private BaseSkuService baseSkuService;
	@Autowired
	private PromotionService promotionService;
	
	@Autowired
	private HttpSession session;
	
	/**
	 * 跳转到商品列表页面
	 * @param request
	 * @return String
	 */
	@RequestMapping(value="list")
	public String list(HttpServletRequest request){
		return "goods/list";
	}
	/**
	 * 跳转到商品列表页面
	 * @param request
	 * @return String
	 */
	@RequestMapping(value="list/detail")
	public String listDetail(HttpServletRequest request){
		return "promotion/detail/goods/list";
	}
	
	/**
	 * 根据条件查找商品列表数据
	 * @param request
	 * @param currPage
	 * @param pageSize
	 * @return Map<String, Object>
	 */
	@RequestMapping(value="/selectList")
	@ResponseBody
	public PageView selectList(HttpServletRequest request,String pageNow, String pageSize, String column, String sort){
		Map<String,Object> resultMap = new LinkedHashMap<String,Object>();
		try{
			String goodsName = request.getParameter("goodsName");
			//查询商品数据
			ParamMap paramMap = getFormMap(ParamMap.class);
			paramMap = toFormMap(paramMap, pageNow, pageSize,paramMap.getStr("orderby"));
			paramMap.put("column", column);
			paramMap.put("sort", sort);
			if(Common.isNotEmpty(goodsName)){
				paramMap.put("name", goodsName);
			}
			List<Goods> goodsList = this.goodsService.selectList(paramMap);
			if(goodsList!=null && goodsList.size()>0){
				for (Goods goods : goodsList) {
					Integer goodsId = goods.getId();
					if(goodsId!=null){
						Map<String, Object> map = new LinkedHashMap<String, Object>();
						map.put("goodsId", goodsId);
						String proTitle = this.getGoodsByPromtion(map);
						goods.setProTitle(proTitle);
					}
				}
			}
			pageView.setRecords(goodsList);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
			logger.info("查询商品数据成功!");
		}catch(Exception e){
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
			logger.error("查询商品数据异常:"+e);
			throw new ScBizException("查询商品数据异常！", e);
		}
		
		return pageView;
	}
	
	/***
	 * 根据id查看商品详细信息
	 * @param id
	 * @return
	 */
	@RequestMapping(value="selectOne",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> selectOne(Integer id){
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
		if(id==null){
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
			logger.warn("查询参数为null！");
		}else {
			try{
				Goods goods = this.goodsService.selectOne(id);
				if(goods!=null){
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS, goods);
					logger.info("查询商品详情成功！");
				}else{
					DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
					logger.warn("查询商品详情失败！");
				}
			}catch(Exception e){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
				logger.error("查询商品数据异常"+e);
				throw new ScBizException("查询商品数据异常！", e);
			}
		}
		return resultMap;
	}
	
	/***
	 * 跳转到添加或编辑商品页面
	 * @param goodsId
	 * @return String
	 */
	@RequestMapping(value="addOrEdit",method=RequestMethod.GET)
	public String addOrEdit(HttpServletRequest request, Integer goodsId){
		try{
			//获取商品分类
			Map<String,Object> goodsClassMap = new HashMap<String, Object>();
			goodsClassMap.put("isEndNode", 1);
			List<GoodsClass> goodsClassList = this.goodsClassService.selectList(goodsClassMap);
			//获取所有的商品单位
			List<GoodsUnit> goodsUnitList = this.goodsUnitService.selectList();
			//获取商品品牌
			List<GoodsBrand> goodsBrandList = this.goodsBrandService.selectList(null);
			//获取基本商品规格
			List<BaseSku> baseSkuList = this.baseSkuService.selectList();
			
			request.setAttribute("goodsClassList", goodsClassList);
			request.setAttribute("goodsUnitList", goodsUnitList);
			request.setAttribute("goodsBrandList", goodsBrandList);
			request.setAttribute("baseSkuList", baseSkuList);
			
			if(goodsId!=null && goodsId!=0){
				//获取商品详情
				Goods goods = this.goodsService.selectOne(goodsId);
				request.setAttribute("goods", goods);
				
				//处理商品相册图片数据
				String imageFiles = goods.getImageFile();
				if(imageFiles!=null){
					String[] goodsImages = imageFiles.split(";");
					List<String> goodsImageList = new ArrayList<String>();
					for(String image : goodsImages){
						goodsImageList.add(image);
					}
					request.setAttribute("goodsImageList", goodsImageList);
				}
				
				//处理商品类型数据
				String type = goods.getType();
				if(type!=null){
					String[] types = type.split("-");
					List<Map<String, Object>> typeMapList = new ArrayList<Map<String, Object>>();
					for(String tp : types){
						Map<String, Object> typeMap = new HashMap<String, Object>();
						if("01".equals(tp)){
							typeMap.put("typeCode", tp);
							typeMap.put("typeName", "特别推荐");
							typeMapList.add(typeMap);
							continue;
						}
						if("02".equals(tp)){
							typeMap.put("typeCode", tp);
							typeMap.put("typeName", "新品热销");
							typeMapList.add(typeMap);
							continue;
						}
						if("03".equals(tp)){
							typeMap.put("typeCode", tp);
							typeMap.put("typeName", "特价商品");
							typeMapList.add(typeMap);
							continue;
						}
						if("04".equals(tp)){
							typeMap.put("typeCode", tp);
							typeMap.put("typeName", "潮流热销");
							typeMapList.add(typeMap);
							continue;
						}
						if("09".equals(tp)){
							typeMap.put("typeCode", tp);
							typeMap.put("typeName", "包邮");
							typeMapList.add(typeMap);
							continue;
						}
						
					}
					request.setAttribute("typeMapList", JsonUtils.listToJson(typeMapList));
				}
			}
			
			return "/goods/edit";
		}catch(Exception e){
			logger.error("查询商品数据异常"+e);
			throw new ScBizException("查询商品数据异常！", e);
		}
	}
	
	/**
	 * 保存商品
	 * @param request
	 * @param goods
	 * @return Map<String, Object>
	 */
	@RequestMapping(value="saveGoods", method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> saveGoods(HttpServletRequest request, Goods goods){
		Map<String,Object> resultMap = new LinkedHashMap<String,Object>();
		
		try{
			String dateTime = DateUtil.formatYMDHMSToString(new Date());
			
			Integer id = goods.getId();	//获取商品id
			int resultInt = 0;
			goods.setShorthand(PinyinUtil.getFirstSpell(goods.getName()));
			
			if(id==null){
				goods.setCreater("零售主管");
				goods.setCreateTime(dateTime);
				goods.setModifier("零售主管");
				goods.setModifyTime(dateTime);
				goods.setIsDelete("0");
				resultInt = this.goodsService.insert(goods);
			}else{
				goods.setModifier("零售主管");
				goods.setModifyTime(dateTime);
				resultInt = this.goodsService.update(goods);
			}
			
			if(resultInt>0){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
				logger.info("商品数据保存成功！");
				return resultMap;
			}else{
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SAVE);
				logger.warn("商品数据保存出错！");
				return resultMap;
			}
			
		}catch(Exception e){
			logger.error("商品数据保存异常！"+e);
			throw new ScBizException("商品数据保存异常！", e);
		}
		
	}
	
	/**
	 * 删除商品
	 * @param ids
	 * @return String
	 */
	@RequestMapping(value="deleteGoods", method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> deleteGoods(String ids){
		Map<String,Object> resultMap = new LinkedHashMap<String,Object>();
		try{
			UserFormMap userFormMap = (UserFormMap)session.getAttribute("userSession");
			String dateTime = DateUtil.formatYMDHMSToString(new Date());
			
			Goods goods = new Goods();
			goods.setIds(ids.split(","));
			goods.setModifier(userFormMap.getStr("userName"));
			goods.setModifyTime(dateTime);
			goods.setIsDelete("1");
			
			int resultInt = goodsService.delete(goods);
			
			if(resultInt>0){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
				logger.info("商品删除成功！");
				return resultMap;
			}else{
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_DELETE);
				logger.warn("商品删除失败！");
				return resultMap;
			}
		}catch(Exception e){
			logger.error("商品数据删除异常！"+e);
			throw new ScBizException("商品数据删除异常！", e);
		}
		
	}
	/**
	 * @Title: addGift
	 * @Description 
	 * @date 2017年4月6日下午 14:32:43
	 * @author LeiJia  
	 * @return String    返回类型
	 */
	@RequestMapping(value="addGift",method=RequestMethod.GET)
	public String addGift(Model model, Integer goodsId){
		try{
			String  goods_id = getPara("id");
			/*try{

				List<PromotionGoodsSkuRecordDto> goodsProInfoList = 	promotionService.getGoodsProInfo(Integer.valueOf(goods_id));
				model.addAttribute("goodsProInfoList", goodsProInfoList);
			}catch(Exception e){
				logger.error("查询商品参与的促销活动数据异常"+e);
				throw new ScBizException("查询商品参与的促销活动数据异常！", e);
			}*/
			model.addAttribute("goods_id", goods_id);
			return "/goods/gift/addGift";
		}catch(Exception e){
			logger.error("查询商品数据异常"+e);
			throw new ScBizException("查询商品数据异常！", e);
		}
	}

	/**
	 * @Title: addEntityDetail
	 * @Description 添加促销明细
	 * @date 2017年4月6日下午 14:30:03
	 * @param model
	 * @param request
	 * @author LeiJia  
	 * @return String    返回类型
	 */
	@ResponseBody
	@RequestMapping(value="gift/goodsProtype",method = RequestMethod.POST)
	public List<PromotionGoodsSkuDto>  goodsProtype() throws Exception {		
		try {
			String goods_id = getPara("goods_id");
			List<PromotionGoodsSkuDto> list = promotionService
					.getGoodsProInfo(Integer.valueOf(goods_id));
			for (PromotionGoodsSkuDto dto : list) {
				String pro_type = dto.getPro_type();
				switch (pro_type) {
				case "0": // 订单满减
					dto.setPro_title("订单满减");
					break;
				case "1": // 商品满减

					dto.setPro_title("商品满减");
					break;
				case "2": // 商品满赠

					dto.setPro_title("商品满赠");
					break;
				case "3": // 商品打折

					dto.setPro_title("商品打折");
					break;
				}
			}
			return list;
		} catch (Exception e) {
			logger.error("添加出校详细数据保存异常！" + e);
			throw new ScBizException("添加出校详细数据保存异常！", e);
		}
	}

	/**
	 * @Title: addEntityDetail
	 * @Description 添加促销明细
	 * @date 2017年4月6日下午 14:30:03
	 * @param model
	 * @param request
	 * @author LeiJia  
	 * @return String    返回类型
	 */
	@ResponseBody
	@RequestMapping(value="gift/addProGift",method = RequestMethod.POST)
	public String addProGift(Model model,HttpServletRequest request, PromotionGoodsSkuDto dto) throws Exception {		
		try{
			dto.setCreate_time(new Date());
			promotionService.insertPromotionGoodsSku(dto);
		}catch(Exception e){
			logger.error("添加出校详细数据保存异常！"+e);
			throw new ScBizException("添加出校详细数据保存异常！", e);
		}
		return "\"success\"";
	}
	
	@RequestMapping(value="getTPlusGoods",method = RequestMethod.GET)
	public void getTPlusGoods(){
		
		String user = "demo";
		String pwd="";
		String account= "000777";
		
		//授权信息
		String appKey = "a4e5cec6-7070-4858-a802-57e13adbd699";
		String appSecret="bjc4b5";
		
		String srvUrl = "http://192.168.0.180:8083/tplus/view/api/v1/";
		
		String jsonstr;
		
		OpenAPI api = new OpenAPI(srvUrl, appKey, appSecret);
		String method = "inventory/Query";
		String data = "{\"param\":{\"Code\":\"830\",\"SelectFields\":\"Id,Code,Name,Shorthand,Specification,DefaultBarCode,InventoryClass.Id,Unit.Id,Productinfo.Id,LatestCost,ImageList,Disabled\"}}";
		
		try {
			//由于T+登录，逻辑有问题，所以这里的逻辑踩用，先登录，再重新登录
			api.login(user, pwd, account);
			api.get("Authorization/ReLogin");//重新登录方法
			
			jsonstr = api.getData(method,data);
			
			System.out.println(jsonstr);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
	}
	
	/***
	 * 根据商品ID查询优惠活动信息
	 * @param map
	 * @return
	 */
	public String getGoodsByPromtion(Map<String, Object> map){
		List<String> proList = promotionService.selectGoodsbyPromotion(map);
		String proTitle = "";
		for (int i = 0; i < proList.size(); i++) {
			//0:订单满减 1:商品满赠 2:商品满减 3:商品打折',
			String proType = proList.get(i);
			if(proType!=null && "1".equals(proType)){
				proTitle+="减"+"、";
			}
			if(proType!=null && "2".equals(proType)){
				proTitle+="增"+"、";
			}
			if(proType!=null && "3".equals(proType)){
				proTitle+="折";
			}
		}
		if(proTitle.endsWith("、")){
//			System.out.println("11111111"+proTitle.substring(0, proTitle.length()-1));
			proTitle = proTitle.substring(0, proTitle.length()-1);
		}
		return proTitle;
	}
	
	
}
